package com.gomoney.auth.controller;

import com.gomoney.auth.common.util.ValidatorUtils;
import com.gomoney.auth.service.SysRoleService;
import com.gomoney.oauth2.common.entity.sys.SysRole;
import com.gomoney.oauth2.common.entity.sys.SysUser;
import com.gomoney.oauth2.common.util.PageUtils;
import com.gomoney.oauth2.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {

    @Autowired
    private SysRoleService roleService;

    /**
     * 角色列表
     */
    @GetMapping("/select")
    @PreAuthorize("hasAuthority('sys:role:select')")
    public R select() {
        List<SysRole> list = roleService.findSysRoleAll();
        return R.ok().put("list", list);
    }

    /**
     * 角色列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = roleService.findSysRoleByPage(params);
        return R.ok().put("page", page);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:role:save')")
    public R save(@RequestBody SysRole role) {
        ValidatorUtils.validateEntity(role);
        SysUser user = getUser();
        role.setUserId(user.getUserId());
        role.setCreateTime(new Date());
        roleService.addSysRole(role);
        return R.ok();
    }

    /**
     * 角色信息
     */
    @GetMapping("/info")
    @PreAuthorize("hasAuthority('sys:role:info')")
    public R info(@RequestParam Map<String, Object> params) {
        SysRole role = roleService.findSysRoleByRoleId(params.get("roleId").toString());
        return R.ok().put("role", role);
    }

    /**
     * 修改角色
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public R update(@RequestBody SysRole role) {
        ValidatorUtils.validateEntity(role);
        SysUser user = getUser();
        role.setUserId(user.getUserId());
        role.setCreateTime(new Date());
        roleService.updateSysRole(role);
        return R.ok();
    }

    /**
     * 删除角色
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public R delete(@RequestBody String[] roleIds) {
        roleService.delSysRoleById(roleIds);
        return R.ok();
    }
}
